import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
// import { component } from 'vue/types/umd'
import Users from '../components/user/userList.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'
import List from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/login' // 重定向
},
{
  path: '/home',
  component: Home,
  redirect: '/welcome',
  children: [
    { path: '/welcome', component: Welcome },
    {
      path: '/users',
      component: Users
    },
    {
      path: '/rights',
      component: Rights
    },
    { path: '/roles', component: Roles },
    { path: '/categories', component: Cate }, // 商品分类
    { path: '/params', component: Params }, // 商品参数
    { path: '/goods', component: List }, // 商品列表
    { path: '/goods/add', component: Add }, // 添加商品
    { path: '/orders', component: Order } // 订单列表
  ]
}, {
  path: '/login',
  component: Login
}]

const router = new VueRouter({
  routes
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next是一个函数，表示放行，有2种用法：1、next()直接放行 2、next('/login')强制跳转到指定路径
  if (to.path === '/login') return next() // 如果是访问的login页面直接放行
  // 获取本机存储的token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login') // 如果没有值则返回NULL,直接强制跳转到登录页面
  next() // 否则继续执行
})

// 暴露给外部组件使用
export default router